﻿using MyMusicPlay._4._0.Operate;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Animation;

namespace MyMusicPlay._4._0
{
    public class Media : BaseClass
    {
        /// <summary>
        /// 歌单信息[Key:歌单名称  Value:歌单路径]
        /// </summary>
        private Dictionary<string, string> AllMusicList = new Dictionary<string, string>();

        //当前显示列表
        public Dictionary<int, Music> CurDisplayList = new Dictionary<int, Music>();
        //当前显示列表名称
        public string MusicListName = "";

        //当前播放列表
        public Dictionary<int, Music> CurPlayingList = new Dictionary<int, Music>();
        private int CurPlayingListMaxKey = 0;
        //当前播放Key
        public int CurPlayingKey = -1;
        public string CurPlayMusicString
        {
            get
            {
                var music = CurPlayingList[CurPlayingKey];
                if (string.IsNullOrEmpty(music.Singer))
                    return music.Name;
                return $"{music.Name} - {music.Singer}";
            }
        }
        public Music GetCurMusic
        {
            get
            {
                if (CurPlayingList.ContainsKey(CurPlayingKey))
                    return CurPlayingList[CurPlayingKey];
                return null;
            }
        }

        //暂停时记录的声音,会在继续播放时重置声音
        public double StopVolume = 0;

        public PlayState playState = PlayState.Stop;

        private MediaElement _mediaElement;

        private MainWindow mainWindow;

        public OrderState orderState = OrderState.order;
        private List<int> PlayOrderList = new List<int>();//播放顺序列表

        public Media(MainWindow main)
        {
            mainWindow = main;
        }

        public void Initialize()
        {
            _mediaElement = new MediaElement();
            _mediaElement.MediaEnded += mainWindow.MediaElement_MediaEnded;
            _mediaElement.MediaOpened += mainWindow.MediaElement_MediaOpened;
            _mediaElement.LoadedBehavior = MediaState.Manual;
            _mediaElement.Width = 0;
            _mediaElement.Height = 0;
            mainWindow.Main_Canvas.Children.Add(_mediaElement);
        }

        /// <summary>
        /// 播放音乐[从头开始]
        /// </summary>
        public void MusicPlaying(int Key)
        {
            if (playState == PlayState.TimeOuting)
                return;
            if (CurPlayingList is { Count: 0 })
                return;
            playState = PlayState.Playing;
            CurPlayingKey = Key;
            if (StopVolume != 0)
                SetVolume(StopVolume);

            var music = CurPlayingList[Key];
            _mediaElement.LoadedBehavior = MediaState.Stop;
            _mediaElement.Source = new Uri(music.Path);
            _mediaElement.LoadedBehavior = MediaState.Play;
        }
        public void MusicPlaying(string id)
        {
            var data = CurPlayingList.FirstOrDefault(u => u.Value.Id == id);
            if (data.Value != null)
            {
                MusicPlaying(data.Key);
            }
        }

        /// <summary>
        /// 切换播放歌单
        /// </summary>
        public void HandoffListAndPlay(int index)
        {
            if (CurDisplayList is { Count: 0 })
                return;
            CurPlayingList = new Dictionary<int, Music>(CurDisplayList);
            CurPlayingListMaxKey = CurPlayingList.Count - 1;
            //重置播放顺序列表
            CreatePlayOrderList();

            MusicPlaying(index);
            //重渲染播放列表背板
            PlayApplication.GetModule<MusicPlayingBoard>().Create();
        }

        /// <summary>
        /// 播放音乐[继续播放]
        /// </summary>
        public void MusicPlaying()
        {
            SetVolume(StopVolume);
            playState = PlayState.Playing;
            _mediaElement.LoadedBehavior = MediaState.Play;
        }

        /// <summary>
        /// 暂停
        /// </summary>
        public void TimeOut()
        {
            playState = PlayState.TimeOuting;
            StopVolume = _mediaElement.Volume;
            double time = 750;
            Task.Run(() =>
            {
                for (int i = 0; i < time / 10; i++)
                {
                    Task.Delay(10).Wait();
                    var curVolume = StopVolume * ((time / 10 - i) / (time / 10));
                    if (i == time / 10 - 1)
                        curVolume = 0;
                    _mediaElement.Dispatcher.Invoke((Action)(() => { _mediaElement.Volume = curVolume; }));
                }
                Task.Delay(1000).Wait();
                _mediaElement.Dispatcher.Invoke((Action)(() =>
                {
                    _mediaElement.LoadedBehavior = MediaState.Pause;
                }));
                playState = PlayState.TimeOut;
            });
            return;
        }

        /// <summary>
        /// 改变音量
        /// </summary>
        public void SetVolume(double volume)
        {
            _mediaElement.Volume = volume;
        }

        /// <summary>
        /// 改变播放时间
        /// </summary>
        public void UpdatePlayPoi(double seconds)
        {
            _mediaElement.Position = new TimeSpan(0, 0, Convert.ToInt32(seconds));
        }

        /// <summary>
        /// 获取音乐播放剩余播放长度
        /// </summary>
        public double GetMusicTimeCount()
        {
            return _mediaElement.NaturalDuration.TimeSpan.TotalMilliseconds - _mediaElement.Position.TotalMilliseconds;
        }

        /// <summary>
        /// 获取全部播放时间
        /// </summary>
        public double GetMusicTimeAllCount()
            => _mediaElement.NaturalDuration.TimeSpan.TotalSeconds;

        #region 歌单
        /// <summary>
        /// 获取歌单路径 by 歌单名称
        /// </summary>
        public string GetMusicListPathByName(string name)
            => AllMusicList.FirstOrDefault(u => u.Key == name).Value;

        /// <summary>
        /// 获取歌单集合中的存储下标
        /// </summary>
        public int GetMusicListIndex(string name)
        {
            int index = 0;
            foreach (var item in AllMusicList)
            {
                if (item.Key == name)
                {
                    return index;
                }
                index++;
            }
            return -1;
        }

        /// <summary>
        /// 添加新歌单
        /// </summary>
        public void AddMusicListToAll(string name, string path)
            => AllMusicList.Add(name, path);
        public void AddMusicListToAll(Dictionary<string, string> keyValuePairs)
            => AllMusicList = new(keyValuePairs);

        /// <summary>
        /// 加载歌单
        /// </summary>
        public void LoadMusicList()
        {
            PlayApplication.GetModule<Rander>().RenderViewOfMusicLists(AllMusicList);
        }

        public void UpdateMusicList(int index, string name, string path)
        {
            DeleteMusicList(index);
            AllMusicList.Add(name, path);
        }

        public void DeleteMusicList(int index)
        {
            int curIndex = 0;
            string key = null;
            foreach (var item in AllMusicList)
            {
                if (index == curIndex)
                {
                    key = item.Key;
                    break;
                }
                curIndex++;
            }
            if (key != null)
            {
                AllMusicList.Remove(key);
            }
        }
        #endregion

        /// <summary>
        /// 创建播放顺序列表
        /// </summary>
        private void CreatePlayOrderList()
        {
            switch (orderState)
            {
                case OrderState.order:
                    PlayOrderList = CurPlayingList.ToListsByKey();
                    break;
                case OrderState.random:
                    PlayOrderList = MyRandom.CreateRandomList(CurPlayingList.ToListsByKey());
                    break;
            }
        }

        /// <summary>
        /// 获取播放顺序列表
        /// </summary>
        public List<int> GetPlayOrderList()
        {
            if (PlayOrderList is { Count: 0 })
            {
                if (CurPlayingList is not { Count: 0 })
                {
                    CreatePlayOrderList();
                }
            }
            else
            {
                if (PlayOrderList.Count != CurPlayingList.Count)
                {
                    CreatePlayOrderList();
                }
            }
            return PlayOrderList;
        }
        public bool RemovePlayOrderList(int key)
            => PlayOrderList.Remove(key);

        /// <summary>
        /// 更改播放顺序
        /// </summary>
        public void UpdateOrderState()
        {
            switch (orderState)
            {
                case OrderState.order:
                    orderState = OrderState.random;
                    break;
                case OrderState.random:
                    orderState = OrderState.order;
                    break;
            }
            mainWindow.CurOrderState.Text = orderState.ToString();
            PlayApplication.GetModule<DispositionApp>().UpdateDispositionOfOrderState((int)orderState);
            CreatePlayOrderList();
        }

        /// <summary>
        /// 插入到播放歌单
        /// </summary>
        /// <param name="curKey"></param>
        public void InsertMusic(int curKey)
        {
            var curSelectMusic = CurDisplayList[curKey];
            if (CurPlayingList.Any(u => u.Value.Id == curSelectMusic.Id))
            {
                InsertMusicByExist(curSelectMusic);
            }
            else
            {
                InsertMusicByNoExist(curSelectMusic);
            }

        }
        /// <summary>
        /// 插入到播放歌单[不存在]
        /// </summary>
        private void InsertMusicByNoExist(Music music)
        {
            CurPlayingListMaxKey++;
            //修改播放列表的下标列表[获取下一首Key][两首的Grid不一样]
            var musicPlaying = PlayApplication.GetModule<MusicPlaying>();
            var key = musicPlaying.GetNextMusic(CurPlayingKey);
            CurPlayingList.Add(CurPlayingListMaxKey, music);

            var index = PlayOrderList.IndexOf(key);
            PlayOrderList.Insert(index, CurPlayingListMaxKey);
            //重渲染
            PlayApplication.GetModule<MusicPlayingBoard>().Create();
        }
        /// <summary>
        /// 插入到播放歌单[存在]
        /// </summary>
        private void InsertMusicByExist(Music music)
        {
            var data = CurPlayingList.FirstOrDefault(u => u.Value.Id == music.Id);
            if (data.Value != null)
            {
                var curIndex = PlayOrderList.IndexOf(CurPlayingKey);
                PlayOrderList.Remove(data.Key);
                PlayOrderList.Insert(curIndex + 1 >= PlayOrderList.Count ? 0 : curIndex + 1, data.Key);
                PlayApplication.GetModule<MusicPlayingBoard>().Create();
            }
        }

        public void UpdateEvent(Action<MediaElement> action)
        {
            action(_mediaElement);
        }



        public enum OrderState
        {
            order = 0,
            random = 1
        }

        public enum PlayState
        {
            Playing,
            TimeOut,
            Stop,
            TimeOuting,
        }
    }
}
